package com.ozero1st;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class type4_quiz extends Activity{
	 	private static final String METHOD_NAME = "sqlSelect";
	    private static final String NAMESPACE = "http://tempuri.org/";
	    private static final String URL = "http://192.168.2.51/WebService1/WebService1.asmx";
	    private static final String SOAP_ACTION = NAMESPACE+METHOD_NAME;
	    private TextView tv;
	    public int aa=1,bb=0;
	    JSONArray array_Q,array_A;
	    ArrayList<String> array_q,array_a = null;
	    Cursor cursor = null;
	    String[] mString,nString;
	    private RadioButton rdoBtn1,rdoBtn2,rdoBtn3,rdoBtn4;
	    private Button btnBack,btnNext;
	    public static SQLiteDatabase db  =null;
	    public Bundle hashitemQTY = new Bundle();
	    
		protected void onDestroy() {
			// TODO OnDestroy
			db.close();
			db = null;
			array_A = null;
			array_Q = null;
			array_a.clear();
			array_q.clear();
	    	super.onDestroy();	
		}
		
		 @Override	
		    public void onCreate(Bundle savedInstanceState) {
		        super.onCreate(savedInstanceState);
		        setContentView(R.layout.list1);
		     // TODO OnCreate
		        
		        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()   

		        .detectDiskReads()   

		        .detectDiskWrites()   

		        .detectNetwork()   // or .detectAll() for all detectable problems   

		        .penaltyLog()   

		        .build());   



		        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()   

		        .detectLeakedSqlLiteObjects()   

		        //.detectLeakedClosableObjects()   

		        .penaltyLog()   

		        .penaltyDeath()   

		        .build());  
		        
		        db = openOrCreateDatabase("school.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
		        db.setVersion(1);
		        db.setLocale(Locale.getDefault());
		        db.setLockingEnabled(true);
		        db.execSQL("DROP TABLE IF EXISTS " + "Question_audio");
		        db.execSQL("DROP TABLE IF EXISTS " + "Answer_audio");
		        db.execSQL("CREATE TABLE if not exists Question_audio(_id INTEGER PRIMARY KEY AUTOINCREMENT , QID NVARCHAR(30) , Q_Name NVARCHAR(50) , Q_Active NVARCHAR(50) , Q_Audio NVARCHAR(50) , Q_Type NVARCHAR(50) , R_Ans NVARCHAR(30));");
		        db.execSQL("CREATE TABLE if not exists Answer_audio(_id INTEGER PRIMARY KEY AUTOINCREMENT ,AID NVARCHAR(30), QID NVARCHAR(30) , A_Name NVARCHAR(50) , A_Point NVARCHAR(50));");
		        db.execSQL("CREATE INDEX if not exists Question_audio_INDEX1 ON Question_audio(QID); ");
		        db.execSQL("CREATE INDEX if not exists Answer_audio_INDEX1 ON Answer_audio(AID); ");
		           
		        call();
		        //ArrayList<String> arr2 = call();
		        tv = (TextView)findViewById(R.id.txtShow);
		        rdoBtn1 = (RadioButton)findViewById(R.id.radio0);
		        rdoBtn2 = (RadioButton)findViewById(R.id.radio1);
		        rdoBtn3 = (RadioButton)findViewById(R.id.radio2);
		        rdoBtn4 = (RadioButton)findViewById(R.id.radio3);
		        //String[] mString = (String[])call().toArray(new String[call().size()]);
		        //tv.setText(mString[0]);
		        //Set option as Multiple Choice. So that user can able to select more the one option from list
		        //lView.setAdapter(new ArrayAdapter<String>(this,
		        //android.R.layout.simple_list_item_multiple_choice, arr2));
		        qString();
		        aString();

		        String[] xString = (String[])array_a.toArray(new String[array_a.size()]);
		        tv.setText(xString[2]+xString[3]);		
		        //lView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		        
		       btnNext = (Button)findViewById(R.id.btnNext);
		       btnBack = (Button)findViewById(R.id.btnBack);
		        
		       				// TODO First	
		       					mString = (String[])array_q.toArray(new String[array_q.size()]);
		    					tv.setText((aa)+"."+mString[0]);			

		    					nString = (String[])array_a.toArray(new String[array_a.size()]);
		    			        rdoBtn1.setText(nString[0]);
		    			        rdoBtn2.setText(nString[1]);
		    			        rdoBtn3.setText(nString[2]);
		    			        rdoBtn4.setText(nString[3]);
		    				
		    				// TODO Button Next
		    				
		    					btnNext.setOnClickListener(new OnClickListener(){
		    						
									public void onClick(View v) {			    				
											mString = (String[])array_q.toArray(new String[array_q.size()]);
											int nx = mString.length;
											if(aa<nx){
											//Question
												if(aa == 0){
													aa++;
												}
					    					tv.setText((aa+1)+"."+mString[0+aa]);
					    					aa++;
											//Answer
						    			    bb = bb+4;
					    					nString = (String[])array_a.toArray(new String[array_a.size()]);			    						
						    					rdoBtn1.setText(nString[bb]);
						    			        rdoBtn2.setText(nString[bb+1]);
						    			        rdoBtn3.setText(nString[bb+2]);
						    			        rdoBtn4.setText(nString[bb+3]);
											}else{
												Toast.makeText(getApplicationContext(), "Click Back", Toast.LENGTH_SHORT).show();
											}
									}
		    						
		    					});

		    				
		    				// TODO Button Back
		    					btnBack.setOnClickListener(new OnClickListener(){

									public void onClick(View v) {
					    					mString = (String[])array_q.toArray(new String[array_q.size()]);
					    					aa--;
					    					if(aa > 0){
					    					tv.setText((aa)+"."+mString[aa-1]);
					    					
					    			        bb = bb-4;
					    					
					    					nString = (String[])array_a.toArray(new String[array_a.size()]);
					    			        rdoBtn1.setText(nString[bb]);
					    			        rdoBtn2.setText(nString[bb+1]);
					    			        rdoBtn3.setText(nString[bb+2]);
					    			        rdoBtn4.setText(nString[bb+3]);
					    					}else{
					    						Toast.makeText(getApplicationContext(), "Click Next", Toast.LENGTH_SHORT).show();
					    					}
									}
		    						
		    					});
		    		}
		 
		 public ArrayList<String> qString(){
				try{
					cursor = db.rawQuery("select * from Question_audio", null );
				}catch(SQLiteException e){
					e.getMessage();
				}
				array_q = new ArrayList<String>();
				if(cursor != null){
					int i = cursor.getCount();
					if(cursor.moveToFirst() && i>0){
						for(int j=0;j<i;j++){
							array_q.add(cursor.getString(cursor.getColumnIndex("Q_Name")));
							cursor.moveToNext();
						} 
					}
				}	
					cursor.close();
			        cursor = null;
			        return array_q;
			}
			
			public ArrayList<String> aString(){
				try{
					cursor = db.rawQuery("select * from Answer_audio", null );
				}catch(SQLiteException e){
					e.getMessage();
				}
				array_a = new ArrayList<String>();
				if(cursor != null){
					int i = cursor.getCount();
					if(cursor.moveToFirst() && i>0){
						for(int j=0;j<i;j++){
							array_a.add(cursor.getString(cursor.getColumnIndex("A_Name")));
							cursor.moveToNext();
						} 
					}
				}	
					cursor.close();
			        cursor = null;
			        return array_a;
			}
	
    public void call()
    {
    	// TODO Call webservice
    		//ArrayList<String> list = null;
			JSONObject jObject = null;    
        	SoapPrimitive responsesData = null; 
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("sql_Q", "select * from Question_audio");
            request.addProperty("sql_A", "select * from Answer_audio");
            
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet=true;
            envelope.setOutputSoapObject(request);

            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
            androidHttpTransport.debug = true; 
            
                 
         // TODO Add to sqllite
            try {

                androidHttpTransport.call(SOAP_ACTION, envelope);
                //list = new ArrayList<String>();
                //ArrayList<String> oz = new ArrayList<String>();
                responsesData = (SoapPrimitive) envelope.getResponse(); 
                jObject  = new JSONObject(responsesData.toString() );
                array_Q = jObject.getJSONArray("Question");
                array_A = jObject.getJSONArray("Answer");   
				int len_Q = array_Q.length();
                if (array_Q != null) { 
                   for (int i=0;i<len_Q;i++){
                	   JSONObject tmp = array_Q.getJSONObject(i);   
                	   
                	   //DELETE
                	   //db.delete("Question","(_id='1')",null);
                	   //db.delete("Question","(_id='2')",null);
                	   //INSERT
                	   ContentValues values = new ContentValues();
                	   values.put("QID", tmp.getString("QID"));
                	   values.put("Q_Name", tmp.getString("Q_Name"));
                	   values.put("Q_Audio", tmp.getString("Q_Audio"));
                	   values.put("Q_Active", tmp.getString("Q_Active"));
                	   values.put("Q_Type", tmp.getString("Q_Type"));
                       values.put("R_Ans", tmp.getString("R_Ans"));
                       db.insert("Question_audio", null, values);
                	   
                       tmp = null;
                	   //list.add(oz.get(i).toString());
                   } 
                } 
                int len2_A = array_A.length();
                if (array_A != null) { 
                   for (int i=0;i<len2_A;i++){
                	   JSONObject tmp = array_A.getJSONObject(i);   
                	   
                	   //DELETE
                	   //db.delete("Answer","(QID='Q1_A3')",null);
                	   //db.delete("Question","(_id='2')",null);
                	   //INSERT
                	   ContentValues values = new ContentValues();
                	   values.put("AID", tmp.getString("AID"));
                	   values.put("A_Name", tmp.getString("A_Name"));
                	   values.put("A_Point", tmp.getString("A_Point"));
                	   values.put("QID", tmp.getString("QID"));
                       db.insert("Answer_audio", null, values);
                	   
                       tmp = null;
                       
                	   //list.add(oz.get(i).toString());
                   } 
                } 
                
                
                request = null;
                envelope = null;
                androidHttpTransport = null;
                jObject = null;
                
            	} catch (SocketException ex) { 
                ex.printStackTrace(); 
                } catch (Exception e) { 
                e.printStackTrace(); 
                }

    }
}
